package com.wmh.baseservice.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdGoods;
import com.wmh.baseservice.admin.service.AdGoodsService;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.UUIDUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantGoods;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.merchant.service.MerchantGoodsService;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.system.service.SysCategoryService;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.pojo.UsGoodsOrder;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsAddressService;
import com.wmh.baseservice.user.service.UsGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "用户端-商城相关接口")
@RestController
@RequestMapping(value = "user/shopMall", produces = "text/plain;charset=utf-8")
public class UsShopMallController {


    @Resource
    private SysCategoryService sysCategoryService;
    @Resource
    private AdGoodsService adGoodsService;
    @Resource
    private UsAddressService usAddressService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantGoodsService merchantGoodsService;
    @Resource
    private UsGoodsOrderService usGoodsOrderService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private SkdGoodsSpecService merchantSpecService;


    @ApiOperation("提交订单")
    @PostMapping("subOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "商品id", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "count", value = "重量", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "province", value = "省", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "city", value = "市", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "area", value = "区", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "address", value = "详细地址", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "name", value = "收货人", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "phone", value = "收货电话", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "1商家商品 2平台商品", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "specId", value = "规格id", required = false),
    })
    @ParameterVerify(notNull = {"id", "province", "city", "area", "address", "name", "phone", "type", "count"})
    public String subOrder(Long id, String province, String city, String area, String address, String name, String phone, Integer type, Integer count, Long specId) {
        Long usId = (Long) request.getAttribute("usId");
        UsGoodsOrder usGoodsOrder = new UsGoodsOrder();
        usGoodsOrder.setUsId(usId).setType(type==1?2:1);

        //商品快照
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        SkdGoodsSpec skdGoodsSpec = null;
        MerchantGoods merchantGoods = null;
        AdGoods adGoods = null;
        if (type == 2) {
            adGoods = adGoodsService.getByIdForUpdate(id);
            if (!CommUtil.checkNull(adGoods) || adGoods.getStatus() != 0) {
                return ReturnBody.error("该商品不存在或已下架");
            }
            //判断库存
            if (CommUtil.checkNull(specId)) {
                skdGoodsSpec = merchantSpecService.getByIdForUpdate(specId);
                if (!CommUtil.checkNull(skdGoodsSpec)) {
                    return ReturnBody.error("规格不存在");
                }
                object.put("specName", skdGoodsSpec.getDescription());
                if (skdGoodsSpec.getInventory() != -1) {
                    if (skdGoodsSpec.getInventory() < count) {
                        return ReturnBody.error("该规格库存不足");
                    }
                }
                skdGoodsSpec.setInventory(skdGoodsSpec.getInventory() - count);
            } else {
                if (adGoods.getInventory() != -1) {
                    if (adGoods.getInventory() < count) {
                        return ReturnBody.error("商品库存不足");
                    }
                    adGoods.setInventory(adGoods.getInventory() - count);
                }
            }
            object.put("id", id);
            object.put("avatar", adGoods.getAvatar());
            object.put("title", adGoods.getTitle());
            object.put("overview", adGoods.getOverview());
            object.put("count", count);
            object.put("price", adGoods.getPrice());
            BigDecimal multiply = adGoods.getPrice().multiply(new BigDecimal(count));
            usGoodsOrder.setRealPrice(multiply);
            usGoodsOrder.setTotalPrice(multiply);
        } else {
            merchantGoods = merchantGoodsService.getByIdForUpdate(id);
            if (!CommUtil.checkNull(merchantGoods) || merchantGoods.getStatus() != 0) {
                return ReturnBody.error("该商品不存在或已下架");
            }
            //判断库存
            if (CommUtil.checkNull(specId)) {
                skdGoodsSpec = merchantSpecService.getByIdForUpdate(specId);
                if (!CommUtil.checkNull(skdGoodsSpec)) {
                    return ReturnBody.error("规格不存在");
                }
                object.put("specName", skdGoodsSpec.getDescription());
                if (skdGoodsSpec.getInventory() != -1) {
                    if (skdGoodsSpec.getInventory() < count) {
                        return ReturnBody.error("该规格库存不足");
                    }
                }
                skdGoodsSpec.setInventory(skdGoodsSpec.getInventory() - count);
            } else {
                if (merchantGoods.getInventory() != -1) {
                    if (merchantGoods.getInventory() < count) {
                        return ReturnBody.error("商品库存不足");
                    }
                    merchantGoods.setInventory(merchantGoods.getInventory() - count);
                }
            }
            object.put("id", id);
            object.put("avatar", merchantGoods.getAvatar());
            object.put("title", merchantGoods.getTitle());
            object.put("overview", merchantGoods.getOverview());
            object.put("count", count);
            object.put("price", merchantGoods.getPrice());
            object.put("merchantId", merchantGoods.getMerchantId());
            usGoodsOrder.setMerchantId(merchantGoods.getMerchantId());
            BigDecimal multiply = merchantGoods.getPrice().multiply(new BigDecimal(count));
            usGoodsOrder.setRealPrice(multiply);
            usGoodsOrder.setTotalPrice(multiply);
        }
        array.add(object);
        usGoodsOrder.setSnapshot(array.toJSONString());
        usGoodsOrder.setOrderNum(UUIDUtil.getTimeId() + UUIDUtil.getLetter());


        //处理地址
        UsAddress usAddress = new UsAddress().setAddress(address).setPhone(phone).setProvince(province).setCity(city).setArea(area).setUsId(usId).setName(name);
        usGoodsOrderService.add(usGoodsOrder, adGoods, merchantGoods, skdGoodsSpec, usAddress);
        return ReturnBody.success(usGoodsOrder.getOrderNum());
    }

    @ApiOperation("购物车结算")
    @PostMapping("settlement")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "shopCar", value = "[{\"shopCarId\":1,\"count\":3,\"id\":1},{\"merchantId\":4,\"count\":4,\"id\":2}]", required = false),
    })
    @ParameterVerify(notNull = "shopCar")
    public String settlement(String shopCar, String province, String city, String area, String address, String name, String phone) {
        Long usId = (Long) request.getAttribute("usId");
        JSONArray array = JSONArray.parseArray(shopCar);
        if (array.size() == 0) {
            return ReturnBody.error("最少添加一个商品");
        }
        //[{"count":3,"id":1},{"count":4,"id":2}]
        JSONArray adGoodsArray = new JSONArray();
        //[{"merchantId":1,"shop":[{"count":3,"id":25},{"count":3,"id":26}]},{"merchantId":2,"shop":[{"count":2,"id":27},{"count":2,"id":28}]}]
        JSONArray merchantGoodsArray = new JSONArray();
        List<AdGoods> adGoodsList = new ArrayList<>();
        List<MerchantGoods> merchantGoodsList = new ArrayList<>();
        List<SkdGoodsSpec> skdGoodsSpecList = new ArrayList<>();
        List<Long> merchantIds = new ArrayList<>();
        array.forEach(item -> {
            JSONObject object = JSONObject.parseObject(item.toString());
            Long merchantId = object.getLong("merchantId");
            Long id = object.getLong("id");
            Integer count = object.getInteger("count");
            Long specId = object.getLong("specId");
            if (CommUtil.checkNull(merchantId)) {
                //查询商品信息 1888
                MerchantGoods rawMerchantGoods = merchantGoodsService.getByIdForUpdate(id);
                if (!CommUtil.checkNull(rawMerchantGoods) || rawMerchantGoods.getStatus() != 0) {
                    throw new ServiceException(String.format("%s商品不存在或已下架", rawMerchantGoods.getTitle()));
                }
                if (CommUtil.checkNull(specId)) {
                    //查询规格库存
                    SkdGoodsSpec skdGoodsSpec = merchantSpecService.getByIdForUpdate(specId);
                    if (!CommUtil.checkNull(skdGoodsSpec)) {
                        throw new ServiceException(String.format("%s规格不存在", skdGoodsSpec.getDescription()));
                    }
                    if (skdGoodsSpec.getInventory() != -1) {
                        if (skdGoodsSpec.getInventory() < count) {
                            throw new ServiceException(String.format("%s规格库存不足", skdGoodsSpec.getDescription()));
                        }
                        skdGoodsSpec.setInventory(skdGoodsSpec.getInventory() - 1);
                        skdGoodsSpecList.add(skdGoodsSpec);
                    }
                } else {
                    //扣减商品库存
                    if (rawMerchantGoods.getHasSpec() != 1) {
                        rawMerchantGoods.setInventory(rawMerchantGoods.getInventory() - count);
                        merchantGoodsList.add(rawMerchantGoods);
                    }
                }
                //商家商品,判断当前id数组里面是否有当前商家id，如果没有，那么往json数组里面添加一个商家商品对象，然后往ids里面添加当前商家id
                if (!merchantIds.contains(merchantId)) {
                    JSONObject merchantObj = new JSONObject(true);
                    JSONArray shopArray = new JSONArray();
                    JSONObject shopObj = new JSONObject(true);
                    merchantObj.put("merchantId", merchantId);
                    shopObj.put("id", id);
                    shopObj.put("count", count);
                    shopObj.put("title", rawMerchantGoods.getTitle());
                    shopObj.put("overview", rawMerchantGoods.getOverview());
                    shopObj.put("price", rawMerchantGoods.getPrice());
                    shopObj.put("avatar", rawMerchantGoods.getAvatar());
                    shopObj.put("merchantId", rawMerchantGoods.getMerchantId());
                    shopArray.add(shopObj);
                    merchantObj.put("shop", shopArray);
                    merchantGoodsArray.add(merchantObj);
                    merchantIds.add(merchantId);
                } else {
                    //如果有，那么往json数组里面对应的商家id对象里的商品数组里面添加一个商品对象
                    merchantGoodsArray.forEach(merchantGoods -> {
                        JSONObject merchantGoodsObj = JSONObject.parseObject(merchantGoods.toString());
                        Long goodsMerchantId = merchantGoodsObj.getLong("merchantId");
                        if (merchantId.equals(goodsMerchantId)) {
                            JSONArray shop = merchantGoodsObj.getJSONArray("shop");
                            JSONObject goodsObj = new JSONObject(true);
                            goodsObj.put("id", id);
                            goodsObj.put("count", count);
                            goodsObj.put("title", rawMerchantGoods.getTitle());
                            goodsObj.put("overview", rawMerchantGoods.getOverview());
                            goodsObj.put("price", rawMerchantGoods.getPrice());
                            goodsObj.put("avatar", rawMerchantGoods.getAvatar());
                            goodsObj.put("merchantId", rawMerchantGoods.getMerchantId());
                            shop.add(goodsObj);
                            merchantGoodsObj.put("merchantId", goodsMerchantId);
                            merchantGoodsObj.put("shop", shop);
                            merchantGoodsArray.remove(merchantGoods);
                            merchantGoodsArray.add(merchantGoodsObj);
                        }
                    });
                }
            } else {
                //查询商品信息
                AdGoods adGoods = adGoodsService.getByIdForUpdate(id);
                if (!CommUtil.checkNull(adGoods) || adGoods.getStatus() != 0) {
                    throw new ServiceException(String.format("%s商品不存在或已下架", adGoods.getTitle()));
                }
                JSONObject goodsObj = new JSONObject();
                goodsObj.put("id", id);
                goodsObj.put("count", count);
                goodsObj.put("title", adGoods.getTitle());
                goodsObj.put("overview", adGoods.getOverview());
                goodsObj.put("price", adGoods.getPrice());
                goodsObj.put("avatar", adGoods.getAvatar());
                adGoodsArray.add(goodsObj);

                if (CommUtil.checkNull(specId)) {
                    //查询规格库存
                    SkdGoodsSpec skdGoodsSpec = merchantSpecService.getByIdForUpdate(specId);
                    if (!CommUtil.checkNull(skdGoodsSpec)) {
                        throw new ServiceException(String.format("%s规格不存在", skdGoodsSpec.getDescription()));
                    }
                    if (skdGoodsSpec.getInventory() != -1) {
                        if (skdGoodsSpec.getInventory() < count) {
                            throw new ServiceException(String.format("%s规格库存不足", skdGoodsSpec.getDescription()));
                        }
                        skdGoodsSpec.setInventory(skdGoodsSpec.getInventory() - count);
                        skdGoodsSpecList.add(skdGoodsSpec);
                    }
                } else {
                    //扣减商品库存
                    if (adGoods.getHasSpec() != 1) {
                        adGoods.setInventory(adGoods.getInventory() - count);
                        adGoodsList.add(adGoods);
                    }
                }
            }
        });


        QueryWrapper<UsAddress> eq = new QueryWrapper<UsAddress>().eq(UsAddress.PROVINCE, province).eq(UsAddress.CITY, city).eq(UsAddress.AREA, area).eq(UsAddress.ADDRESS, address).eq(UsAddress.NAME, name)
                .eq(UsAddress.PHONE, phone).eq(UsAddress.US_ID, usId);
        UsAddress usAddress = usAddressService.getOneForUpdate(eq);
        if (!CommUtil.checkNull(usAddress)) {
            if (!usAddressService.save(usAddress)) {
                return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
            }
        }
        List<String> strings = usGoodsOrderService.shopCar(usAddress.getId(), usId, adGoodsArray, merchantGoodsArray, adGoodsList, merchantGoodsList, skdGoodsSpecList);
        if (strings.size() == 0) {
            return ReturnBody.error("购物车订单提交失败");
        }
        return ReturnBody.success(strings);
    }

    @ApiOperation("取消订单")
    @PostMapping("cancelOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String cancelOrder(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsGoodsOrder usGoodsOrder = usGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGoodsOrder>().eq(UsGoodsOrder.ORDER_NUM, orderNum));
        if (!CommUtil.checkNull(usGoodsOrder) || !usGoodsOrder.getUsId().equals(usId) || usGoodsOrder.getStatus() != 0) {
            return ReturnBody.error("订单状态错误");
        }
        usGoodsOrder.setStatus(-1);
        if (!usGoodsOrderService.updateById(usGoodsOrder)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("余额支付")
    @PostMapping("balancePay")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNumList", value = "订单号数组", required = true),
    })
    @ParameterVerify(notNull = "orderNumList")
    public String balancePay(String orderNumList) {
        Long usId = (Long) request.getAttribute("usId");
        JSONArray array = JSONArray.parseArray(orderNumList);
        if (array.size() == 0) {
            return ReturnBody.error("订单为空");
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        final BigDecimal[] total = {new BigDecimal(0)};
        array.forEach(orderNum -> {
            UsGoodsOrder usGoodsOrder = usGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGoodsOrder>().eq(UsGoodsOrder.ORDER_NUM, orderNum).eq(UsGoodsOrder.US_ID, usId));
            if (!CommUtil.checkNull(usGoodsOrder) || usGoodsOrder.getStatus() != 0) {
                throw new ServiceException("订单不存在或状态错误");
            }
            total[0] = total[0].add(usGoodsOrder.getRealPrice());
        });
        if (usInfo.getBalance().compareTo(total[0]) < 0) {
            return ReturnBody.error("用户余额不足");
        }
        usGoodsOrderService.balancePay(total[0], usInfo, array);
        return ReturnBody.success();
    }

    @ApiOperation("确认收货")
    @PostMapping("theGoods")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "orderNum", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String theGoods(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsGoodsOrder usGoodsOrder = usGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        if (!CommUtil.checkNull(usGoodsOrder) || !usGoodsOrder.getUsId().equals(usId)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (usGoodsOrder.getStatus()!=2){
            return ReturnBody.error("订单状态错误");
        }
        usGoodsOrder.setStatus(3);
        usGoodsOrderService.theGoods(usGoodsOrder);
        return ReturnBody.success();
    }


}
